package com.example.video.file_server.common.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.video.common.config.RabbitMQ.Common;
import com.example.video.common.config.RabbitMQ.VideoTranscode;
import com.example.video.common.entity.FileResourceInfo;
import com.example.video.common.util.ResponseWrap;
import com.example.video.common.util.ResponseWrapUtil;
import com.example.video.file_server.common.FFmpeg.domain.VideoMetaInfo;
import com.example.video.file_server.service.IFileService;
import com.example.video.video_server.entity.VideoResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * <p>
 * amqp 消费者
 * <p/>
 *
 * @author : yj
 */
@Component
@Slf4j
public class FileRabbitListenerConfig {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private IFileService iFileService;

    @RabbitListener(queues = VideoTranscode.REQUEST_QUEUE)
    public void mergeAndTranscode(String string) {
        FileResourceInfo fileResourceInfo = JSONObject.parseObject(string, FileResourceInfo.class);
        ResponseWrap responseWrap = ResponseWrapUtil.error("error",fileResourceInfo);
        if (fileResourceInfo != null && !StringUtils.isEmpty(fileResourceInfo.getUrl())){
            try {
                VideoMetaInfo videoMetaInfo = iFileService.mergeAndTranscode(fileResourceInfo.getUrl(),fileResourceInfo.getContentType().split("/")[1]);
                if (videoMetaInfo != null) {
                    fileResourceInfo.setUrl(videoMetaInfo.getUrl());
                    fileResourceInfo.setBucketName(videoMetaInfo.getBucketName());
                    fileResourceInfo.setObjectName(videoMetaInfo.getObjectName());
                    responseWrap = ResponseWrapUtil.success(fileResourceInfo);
                }
            }catch (Exception e){
                log.error("视频转码错误{},资源id:{}",e.getMessage(),fileResourceInfo.getRelationId());
            }
        }
        amqpTemplate.convertAndSend(Common.EXCHANGE, VideoTranscode.RESPONSE_KEY, JSON.toJSONString(responseWrap));
    }

}
